package info.daveturner;


import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class XMLUtils {
  
  public static Document getDomParser(String xml) throws Exception{
    //get the factory
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    Document dom=null;
    InputSource xmlDoc = new InputSource( new StringReader( xml ) );
    //Using factory get an instance of document builder
    DocumentBuilder db = dbf.newDocumentBuilder();
      
    //parse using builder to get DOM representation of the XML file
    dom = db.parse(xmlDoc);
        
    if(dom == null){
      throw new Exception ("unable to parse dom");
    }
    
    return dom;
  }
  
  public static String getTextValue(Element ele, String tagName) {
    String textVal = null;
    NodeList nl = ele.getElementsByTagName(tagName);
    if(nl != null && nl.getLength() > 0) {
      Element el = (Element)nl.item(0);
      textVal = el.getFirstChild().getNodeValue();
    }

    return textVal;
  }
}
